﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MyToolkit.Com;
using WeifenLuo.WinFormsUI.Docking;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor.Actions;
using Bing.Toolkit.Data;
using Bing.Toolkit.Data.SQL;
using MyToolkit.Com;

namespace MyToolkit
{
    public partial class FrmEntityBuilder : DockContent
    {
        private DatabaseConnection _dc;
        private string _tableName;
        private DbTable _dbTable;

        public FrmEntityBuilder(DatabaseConnection dc, string tableName)
        {
            _dc = dc;
            _tableName = tableName;
            InitializeComponent();
        }

        public void SetTemplateContent(string content)
        {
            this.textEditorControl1.Text = content;
        }

        private void FrmEntityBuilder_Load(object sender, EventArgs e)
        {
            this.TabText = _tableName;
            groupBox1.Text += _dc.DataBaseName + "->" + _tableName;

            this.textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            this.textEditorControl1.Encoding = Encoding.Default;
            this.textEditorControl2.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            this.textEditorControl2.Encoding = Encoding.Default;

            LoadDataScheme();
        }

        private void LoadDataScheme()
        {
            #region SQL
            var strSQL = @"SELECT   D.name as table_name, ISNULL(F.value, '') as table_desc, A.colorder as column_index, A.name as column_name, 
CASE WHEN COLUMNPROPERTY(A.ID,A.NAME, 'ISIDENTITY ') = 1 THEN 1 ELSE 0 END as is_identity, 
CASE WHEN EXISTS(
	SELECT 1 FROM SYSOBJECTS WHERE XTYPE= 'PK ' AND PARENT_OBJ=A.ID AND NAME IN ( 
		SELECT NAME FROM SYSINDEXES WHERE INDID IN(SELECT INDID FROM SYSINDEXKEYS WHERE ID = A.ID AND COLID=A.COLID
		)
	)
) THEN 1 ELSE 0 END AS is_pk, 
B.NAME as type_name, A.LENGTH as type_length, 
CASE WHEN A.ISNULLABLE=1 THEN 1 ELSE 0 END as is_null, ISNULL(E.TEXT, '') as column_def_val, 
ISNULL(G.[VALUE], '') as column_desc 
FROM   
SYSCOLUMNS   A 
LEFT   JOIN   
SYSTYPES   B   
ON   
A.XUSERTYPE=B.XUSERTYPE 
INNER   JOIN   
SYSOBJECTS   D   
ON   
A.ID=D.ID     AND   D.XTYPE= 'U '   AND     D.NAME <> 'DTPROPERTIES ' 
LEFT   JOIN   
SYSCOMMENTS   E   
ON   
A.CDEFAULT=E.ID 
LEFT   JOIN   
sys.extended_properties   G   
ON   
A.ID=G.major_id   AND   A.COLID=G.minor_id     
LEFT   JOIN   
sys.extended_properties   F   
ON   
D.ID=F.major_id   AND   F.minor_id=0 
WHERE d.name = {0}
ORDER   BY   
A.ID,A.COLORDER";
            #endregion

            using (var db = new SQLServerDAO(_dc.ConnectionString))
            {
                _dbTable = new DbTable();

                _dbTable.Name = _tableName;

                var dataResult = db.Query(strSQL, _tableName);

                foreach (var subItem in dataResult)
                {
                    DbTableColumn column = new DbTableColumn();

                    column.Name = subItem.AsValue<string>("column_name");
                    column.Length = subItem.AsValue<int>("type_length");
                    column.IsNull = subItem.AsValue<int>("is_null") == 1;
                    column.IsPK = subItem.AsValue<int>("is_pk") == 1;
                    column.DatabaseType = subItem.AsValue<string>("type_name");
                    column.CSharpType = TypeHelper.GetCSharpType(column.DatabaseType);
                    column.IsIdentity = subItem.AsValue<int>("is_identity") == 1;
                    column.DefaultValue = subItem.AsValue<string>("column_def_val");
                    column.Description = subItem.AsValue<string>("column_desc");

                    _dbTable.Columns.Add(column);
                }
            }

            this.dataGridView1.DataSource = _dbTable.Columns;
        }
    }
}
